﻿using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PlanningGIS.Util;

namespace PlanningGIS.Engine.Controls
{
    /// <summary>
    /// 绘制工具构建对象
    /// </summary>
    public class ToolCreator
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="control">要构建的控件，目前只支持ButtonX,ButtonItem,Bar</param>
        /// <param name="hook">地图关联对象</param>
        public ToolCreator(dynamic control, object hook)
        {
            _Control = control;
            HideForm = true;
            _Name = "_TLCT" + DateTime.Now.ToString("HHmmss");
            try
            {
                _HookHelper = new HookHelper();
                _HookHelper.Hook = hook;
            }
            catch 
            {
                _HookHelper = null;
            }            
        }

        /// <summary>
        /// 工具容器控件
        /// </summary>
        private dynamic _Control = null;

        /// <summary>
        /// 地图关联对象
        /// </summary>
        private IHookHelper _HookHelper = null;

        /// <summary>
        /// 是否隐藏控件所在的窗体
        /// </summary>
        public bool HideForm { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private string _Name = "_ToolCreator";

        /// <summary>
        /// 绘制的对象
        /// </summary>
        public IElement DrawElement { get; set; }

        /// <summary>
        /// 绘制的空间对象
        /// </summary>
        public IGeometry Geometry { get; set; }
        
        /// <summary>
        /// 绘制完成事件
        /// </summary>
        public event DrawFinishedEventHandler DrawFinished;

        /// <summary>
        /// 清除之前绘制的对象
        /// </summary>
        public event NullParameter ClearOld;

        /// <summary>
        /// 获取或设置当前选择的绘制工具对象
        /// </summary>
        public ESRI.ArcGIS.SystemUI.ICommand CurrentCommand { get; set; }

        /// <summary>
        /// 创建自定义的绘制控件
        /// </summary>
        /// <param name="tools">要创建的控件</param>
        /// <param name="isToMap">是否在地图上显示</param>
        public void Create(List<ValueName> tools, bool isToMap = true)
        {
            if (tools == null || tools.Count == 0) return;
            string dllname = "PlanningGIS.Engine.Controls";
            foreach (ValueName v in tools)
            {
                ButtonItem btn = new ButtonItem(v.Value, v.Name);
                btn.Tag = Activator.CreateInstance(Type.GetType(dllname + "." + btn.Name + "," + dllname));
                if (btn.Tag is ESRI.ArcGIS.SystemUI.ICommand)
                    (btn.Tag as ESRI.ArcGIS.SystemUI.ICommand).OnCreate(_HookHelper.Hook);
                if (btn.Tag is IDrawGeometry)
                {
                    IDrawGeometry dg = (btn.Tag as IDrawGeometry);
                    dg.ClearElements += Clear;
                    dg.DrawFinished += ToolCreator_DrawFinished;
                    dg.IsToMap = isToMap;
                }
                string imagename = v.Value.Replace("ToolDraw", "New");
                Bitmap bmp = (Bitmap)(Properties.Resources.ResourceManager.GetObject(imagename));
                bmp.MakeTransparent();
                btn.Image = bmp;
                btn.Tooltip = v.Name;
                btn.Click += new EventHandler(ButtonClick);
                _Control.SubItems.Add(btn);
                if (CurrentCommand == null)
                    CurrentCommand = btn.Tag as ESRI.ArcGIS.SystemUI.ICommand;   
            }
            _Control.Click += new EventHandler(Control_Click);
        }

        /// <summary>
        /// 绘制完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolCreator_DrawFinished(object sender, DrawArgs e)
        {
            SetFormVisiable(_Control, FormWindowState.Normal);
            DrawElement = e.DrawElement;
            IElementProperties ep = DrawElement as IElementProperties;
            ep.Name = _Name + DateTime.Now.ToString("HHmmssttt");
            Geometry = e.Geometry;
            if (DrawFinished != null) DrawFinished(this, e);
        }

        /// <summary>
        /// 控件点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Control_Click(object sender, EventArgs e)
        {
            SetFormVisiable(_Control, FormWindowState.Minimized);
            if (_HookHelper.Hook != null && CurrentCommand != null)
                CurrentCommand.OnClick();
        }

        /// <summary>
        /// 按钮项点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonClick(object sender, EventArgs e)
        {
            ButtonItem btn = (ButtonItem)sender;
            if (btn.Tag == null) return;
            if (!btn.Name.Equals(_Control.Name))
            {
                _Control.Image = btn.Image;
                _Control.Tag = btn.Tag;
            }
            SetFormVisiable(_Control, FormWindowState.Minimized);
            Clear();
            CurrentCommand = btn.Tag as ESRI.ArcGIS.SystemUI.ICommand;
            if (_HookHelper.Hook != null && CurrentCommand != null)
                CurrentCommand.OnClick();
        }

        /// <summary>
        /// 设置绘制按钮Enable
        /// </summary>
        public void SetToolEnable(string toolName, bool enable)
        {
            int idx = _Control.SubItems.IndexOf(toolName);
            if (idx != -1)
                _Control.SubItems[idx].Enabled = enable;
        }

        /// <summary>
        /// 设置控件所在窗体的显示状态
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="state"></param>
        private void SetFormVisiable(dynamic ctl, FormWindowState state)
        {
            if (!HideForm) return;
            try
            {
                if (ctl == null) return;
                if (ctl is ButtonItem)
                {
                    SetFormVisiable(ctl.ContainerControl, state);
                }
                else
                {
                    if (ctl.Parent == null) return;
                    if (ctl.Parent is Form)
                        ((Form)ctl.Parent).WindowState = state;
                    else
                        SetFormVisiable(ctl.Parent, state);
                }                
            }
            catch 
            {
                
            }
            
        }

        /// <summary>
        /// 清除
        /// </summary>
        public void Clear()
        {
            if (DrawElement == null || _HookHelper == null) return;
            IGraphicsContainer grp = _HookHelper.ActiveView.GraphicsContainer;
            grp.Reset();
            IElement ele = null;
            while ((ele = grp.Next()) != null)
            {
                IElementProperties ep = ele as IElementProperties;
                if (string.IsNullOrWhiteSpace(ep.Name)) continue;
                if (ep.Name.StartsWith(_Name)) grp.DeleteElement(ele);            
            }            
            _HookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics | esriViewDrawPhase.esriViewGraphicSelection, null, _HookHelper.ActiveView.Extent);
            DrawElement = null;
        }

    }
}
